<?php

namespace App\Imports\Fy;

use App\Models\Fy\FyRegionModel;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToCollection;

class FyRegionImport implements ToCollection
{
    /**
     * @param Collection $collection
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function collection(Collection $collection)
    {
        $collection->shift();


        $contents = $collection->groupBy(0)->map(function ($v, $code) {
            return [
                "code"  => (string)$code,
                "pCode" => "",
                "level" => 1,
                "name"  => $v->getIterator()->current()->get(3),
                "child" => $v->groupBy(1)->map(function ($v, $code) {
                    return [
                        "code"  => (string)$code,
                        "pCode" => (string)$v->getIterator()->current()->get(0),
                        "level" => 2,
                        "name"  => $v->getIterator()->current()->get(4),
                        "child" => $v->groupBy(2)->map(function ($v, $code) {
                            return [
                                "code"           => (string)$code,
                                "pCode"          => (string)$v->getIterator()->current()->get(1),
                                "level"          => 3,
                                "name"           => $v->getIterator()->current()->get(5),
                                "regionBankCode" => $v->getIterator()->current()->get(6),
                            ];
                        })->values()
                    ];
                })->values()
            ];
        })->values()->toJson(JSON_UNESCAPED_UNICODE);

        logFile($contents, "fy", "fyRegion", "json");


//        $collection->each(function ($v, $k) {
//            echo "第 {$k} 条" . PHP_EOL;
//            for ($i = 1; $i <= 3; $i++) {
//                try {
//                    $data = [
//                        "code"           => (string)$v->get($i - 1),
//                        "pCode"          => (string)$v->get($i - 2, ""),
//                        "name"           => (string)$v->get(2 + $i),
//                        "level"          => (int)$i,
//                        "regionBankCode" => (string)($i == 3 ? $v->get(6) : "")
//                    ];
//                    FyRegionModel::query()->insertGetId($data);
//                } catch (\Exception $exception) {
//                }
//            }
//        });
    }
}
